package net.bitdixit.ywu.library;

import net.bitdixit.ywu.R;
import net.bitdixit.ywu.preferences.AppPreferences;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;

public class AsanaInfoActivity extends Activity
implements OnGestureListener
{
	public static String INTENT_ASANA = "asana";
	public static String INTENT_VIEW = "view";
	
	private GestureDetector  gestureScanner;	
	private Asana            asana;
    private AsanaLibrary     library;
    private AsanaLibraryView libraryView;
    private AppPreferences   appPreferences;
    private SetAsanaBitmapTask setAsanaBitmapTask;
    
	private class SetAsanaBitmapTask extends AsyncTask<Asana, Void, Object>
	{
	     Asana theAsana;
	     protected void onPostExecute(Object result)
	     {
            TextView text = (TextView) findViewById(R.id.infoAsanaName);
	    	 if (result instanceof Bitmap)
	    	 {
	    		 ImageView img1 = (ImageView) findViewById(R.id.infoAsanaImage1);
	    		 img1.setImageBitmap((Bitmap)result);
	    		 text.setText(asana.getName(AsanaLibrary.LANG_EN).trim());

	    	 } 
	    	 if (result instanceof Exception )
	    	 {
	    	    text.setText(((Exception)result).getMessage());
	    	 }
	     }
		@Override
		protected Object doInBackground(Asana... params) {
			 theAsana = params[0];
			 try
	         {
	  	        TextView text = (TextView) findViewById(R.id.infoAsanaName);
		    	text.setText("Downloading image...");
	    	    return theAsana.getImage();
	         } catch (Exception e)
	         {
	        	 return e;
	         }
		}
	}
        
    
    
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev){
        super.dispatchTouchEvent(ev);
        return gestureScanner.onTouchEvent(ev);
    }

    public void init()
    {
        Bundle bundle = getIntent().getExtras();
        libraryView.viewData().unserialize(bundle.getString(INTENT_VIEW));
        libraryView.apply();
        asana = libraryView.get(bundle.getString(INTENT_ASANA));
        setAsanaBitmapTask = null;
        setContent();    	
    }
    
	@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.asana_info);
        
        appPreferences = new AppPreferences(getApplicationContext());
        gestureScanner = new GestureDetector(this);
        
        library = new AsanaLibrary(this);
        libraryView = new AsanaLibraryView(library, appPreferences);
        
        init();
    }
	@Override
	protected void onResume()
	{
        super.onResume();
        init();
	};
	
	
	public void setContent()
	{
        final TextView text = (TextView) findViewById(R.id.infoAsanaName);

        CheckBox checkBox = (CheckBox) findViewById(R.id.stared);
    	checkBox.setChecked(appPreferences.isAsanaStared(asana.getId()));
    	checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
    	{
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				appPreferences.setAsanaStared(asana.getId(), arg1);
			}
    	});
    	getWindow().setTitle(asana.getName(AsanaLibrary.LANG_SK).trim());
    	text.setText(asana.getName(AsanaLibrary.LANG_EN).trim());
    	if (asana.isImageCached())
    	{
   		 	ImageView img1 = (ImageView) findViewById(R.id.infoAsanaImage1);
   		 	try
   		 	{
   		 		img1.setImageBitmap(asana.getImage());
   		 	} catch (Exception forget)
   		 	{
   		 		
   		 	}
    	}
    	else
    	{
    		if (setAsanaBitmapTask!=null && setAsanaBitmapTask.getStatus()!=Status.FINISHED)
    			setAsanaBitmapTask.cancel(true);
    		setAsanaBitmapTask=new SetAsanaBitmapTask();
    		setAsanaBitmapTask.execute(asana);
    	}
	}
	
    @Override
    public boolean onTouchEvent(MotionEvent me)
    {
 
        return gestureScanner.onTouchEvent(me);
    }	
	
	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	public float abs(float v) { if (v<0) return -v; return v; }
	
	long lastGestureProcessed=0;
	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		
		if (abs(distanceX)>abs(distanceY)
			&& abs(distanceX)>10
			&& System.currentTimeMillis()-lastGestureProcessed>200)
		{
			asana = libraryView.next(asana, distanceX>10);
			setContent();
			lastGestureProcessed=System.currentTimeMillis();
		}

		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}
}
